package work.linruchang.oauthclientproject.config.interceptor;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Basic认证
 * 本系统用户登录
 * @author LinRuChang
 * @version 1.0
 * @date 2022/08/04
 * @since 1.8
 **/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class BasicAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean authStatusFlag = false;
        String authorization = request.getHeader("Authorization");
        String authType = null;
        String authInfoCredentials = null;
        String userName = null;
        List<String> authorizationInfos = StrUtil.splitTrim(authorization, StrUtil.SPACE);
        if(CollUtil.size(authorizationInfos) == 2) {
            authType = authorizationInfos.get(0);
            authInfoCredentials = authorizationInfos.get(1);
            if (StrUtil.isNotBlank(authInfoCredentials)) {
                if (StrUtil.equalsAnyIgnoreCase(authType, "BASIC")) {
                    String authInfo = Base64.decodeStr(authInfoCredentials);
                    List<String> authInfos = StrUtil.splitTrim(authInfo, StrUtil.COLON);
                    userName = CollUtil.size(authInfos) >= 2 ? authInfos.get(0) : null;
                    String password =  CollUtil.size(authInfos) >= 2 ? authInfos.get(1) : null;

                    //这里自行获取数据库中的用户、密码信息进行校验是否正确
                    Dict dbUserInfo = getUserInfo(userName);
                    if(dbUserInfo != null && StrUtil.equals(password,dbUserInfo.getStr("password"))) {
                        authStatusFlag = true;
                    }
                }
            }
        }



        //认证失败
        if (!authStatusFlag) {
            response.setHeader("WWW-Authenticate",StrUtil.format("{} realm=\"rights of administrators\"", StrUtil.blankToDefault(authType,"BASIC")));
            response.setStatus(401);
            return false;
        }
        //添加cookie信息给用户 == 当前用户名
        if(!StrUtil.containsIgnoreCase(request.getRequestURI(),"logout")) {
            Cookie userNameCookie = new Cookie("userName", userName);
            userNameCookie.setPath("/");
            response.addCookie(userNameCookie);

            Cookie userNameDescCookie = new Cookie("userNameDesc", "管理员");
            userNameDescCookie.setPath("/");
            response.addCookie(userNameDescCookie);
        }
        return authStatusFlag;
    }


    public Dict getUserInfo(String userName) {
        if(StrUtil.equals(userName,"admin")) {
            return Dict.create()
                    .set("userName","admin")
                    .set("password", "admin123");

        }
        return null;
    }
}
